﻿using System.Security.Claims;

namespace ELF.Gateway.Jwt;

public class GatewayMiddleware
{
    private readonly RequestDelegate _next;
    private readonly GatewayJwtService _jwtService;

    public GatewayMiddleware(RequestDelegate next, GatewayJwtService jwtService)
    {
        _next = next;
        _jwtService = jwtService;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (context.User.Identity?.IsAuthenticated == true)
        {
            // 生成含用户ID的网关JWT
            var gatewayToken = _jwtService.CreateGatewayToken(context.User);
            // 替换请求头
            context.Request.Headers["Authorization"] = $"Bearer {gatewayToken}";
        }

        await _next(context);
    }
}